/* eslint-disable no-unused-vars */
import { create } from 'zustand'
import { createJSONStorage, persist } from 'zustand/middleware'
import { BattleUser, Battle } from '@/types/battle'

// 战斗记录列表状态
export interface BattleRecordsState {
  items: Battle[]
  currentPage: number
  totalPages: number
  recordsPerPage: number
  lastFetchTime: number
  cachedPage: number
  isFromNavigation: boolean
  setRecords: (items: Battle[], page: number, totalPages: number) => void
  setCurrentPage: (page: number) => void
  setFromNavigation: (isFromNavigation: boolean) => void
  clearCache: () => void
  isDataValid: () => boolean
  shouldRefetch: (page: number) => boolean
  initializeFromCache: () => void
}

// 用户状态
export interface UserState {
  storeUsers: BattleUser[]
  addUser: (user: BattleUser | null) => BattleUser | null
  addUsers: (users: BattleUser[]) => BattleUser[]
  contains: (user: BattleUser) => boolean
  contains_by_name: (name: string) => boolean
  check_new_users: (names: string[]) => string[]
  update_user: (user: BattleUser) => boolean
  clear: () => void
}

// 创建一个自定义的存储，带有过期逻辑
// const createExpiringStorage = (storage: Storage, expireIn: number) => {
//   return {
//     getItem: (name: string) => {
//       const item = storage.getItem(name)
//       if (!item) return null

//       const { value, expiry } = JSON.parse(item)
//       if (Date.now() > expiry) {
//         storage.removeItem(name)
//         return null
//       }
//       return value
//     },
//     setItem: (name: string, value: unknown) => {
//       const expiry = Date.now() + expireIn
//       const item = JSON.stringify({ value, expiry })
//       storage.setItem(name, item)
//     },
//     removeItem: (name: string) => {
//       storage.removeItem(name)
//     }
//   }
// }

// 检查 sessionStorage 是否可用
// const isSessionStorageAvailable = () => {
//   try {
//     const testKey = '__test__'
//     sessionStorage.setItem(testKey, testKey)
//     sessionStorage.removeItem(testKey)
//     return true
//   } catch (e) {
//     return false
//   }
// }

// 创建用户状态
export const battleUserStore = create<UserState>()(
  persist(
    (set, get) => ({
      storeUsers: [],
      addUser: (user: BattleUser | null) => {
        if (user && !get().storeUsers.some((u) => u.id === user.id)) {
          set((state) => ({
            storeUsers: [...state.storeUsers, user]
          }))
          return user
        }
        return null
      },
      addUsers: (users: BattleUser[]) => {
        const newUsers = users.filter(
          (user) => !get().storeUsers.some((u) => u.id === user.id)
        )
        set((state) => ({
          storeUsers: [...state.storeUsers, ...newUsers]
        }))
        return newUsers
      },
      contains: (user: BattleUser) => {
        return get().storeUsers.some((u) => u.id === user.id)
      },
      contains_by_name: (name: string) => {
        return get().storeUsers.some((u) => u.name === name)
      },
      check_new_users: (names: string[]) => {
        const currentUsers = get().storeUsers.map((u) => u.name)
        const newUsers = names.filter((name) => !currentUsers.includes(name))
        return newUsers
      },
      update_user: (user: BattleUser) => {
        const index = get().storeUsers.findIndex((u) => u.id === user.id)
        if (index < 0) return false
        console.log(`update user ${user.name}`)
        const newUsers = [...get().storeUsers]
        newUsers[index] = user
        set({ storeUsers: newUsers })
        return true
      },
      clear: () => {
        set({ storeUsers: [] })
      }
    }),
    {
      name: 'battle_user_v3',
      // storage: isSessionStorageAvailable()
      //   ? createExpiringStorage(sessionStorage, 2 * 60 * 60 * 1000)
      //   : undefined
      storage: createJSONStorage(() => sessionStorage)
    }
  )
)

// 创建战斗记录状态管理
export const battleRecordsStore = create<BattleRecordsState>()(
  persist(
    (set, get) => ({
      items: [],
      currentPage: 1,
      totalPages: 1,
      recordsPerPage: 10,
      lastFetchTime: 0,
      cachedPage: 0,
      isFromNavigation: false,
      setRecords: (items: Battle[], page: number, totalPages: number) => {
        set({
          items,
          currentPage: page,
          totalPages,
          lastFetchTime: Date.now(),
          cachedPage: page
        })
      },
      setCurrentPage: (page: number) => {
        set({ currentPage: page })
      },
      setFromNavigation: (isFromNavigation: boolean) => {
        set({ isFromNavigation })
      },
      clearCache: () => {
        set({
          items: [],
          currentPage: 1,
          totalPages: 1,
          lastFetchTime: 0,
          cachedPage: 0,
          isFromNavigation: false
        })
      },
      isDataValid: () => {
        const { lastFetchTime } = get()
        // 缓存有效期为5分钟
        return Date.now() - lastFetchTime < 5 * 60 * 1000
      },
      shouldRefetch: (page: number) => {
        const { cachedPage, items, isDataValid } = get()
        // 如果页码不同，或数据过期，或没有数据，则需要重新获取
        return page !== cachedPage || !isDataValid() || items.length === 0
      },
      initializeFromCache: () => {
        const { isFromNavigation, isDataValid, cachedPage } = get()
        // 如果是从导航返回且数据有效，则保持缓存的页码
        if (isFromNavigation && isDataValid()) {
          set({ currentPage: cachedPage })
        } else {
          // 否则重置到第一页
          set({ currentPage: 1 })
        }
        // 清除导航标志
        set({ isFromNavigation: false })
      }
    }),
    {
      name: 'battle_items_cache',
      storage: createJSONStorage(() => sessionStorage)
    }
  )
)
